<template>
  <div class="dashboard">
    <!-- 统计卡片 -->
    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-icon users">
          <i class="fas fa-users"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.totalUsers }}</div>
          <div class="stat-label">总用户数</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon products">
          <i class="fas fa-box"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.totalProducts }}</div>
          <div class="stat-label">商品总数</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon orders">
          <i class="fas fa-shopping-cart"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.totalOrders }}</div>
          <div class="stat-label">订单总数</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon revenue">
          <i class="fas fa-dollar-sign"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">¥{{ formatMoney(stats.totalRevenue) }}</div>
          <div class="stat-label">总收入</div>
        </div>
      </div>
    </div>
    
    <!-- 主要内容区域 -->
    <div class="main-grid">
      <!-- 最近订单 -->
      <div class="content-card">
        <div class="card-header">
          <h3 class="card-title">最近订单</h3>
          <router-link to="/admin/orders" class="view-all-link">
            查看全部 <i class="fas fa-arrow-right"></i>
          </router-link>
        </div>
        <div class="card-content">
          <div v-if="loading.orders" class="loading-state">
            <div class="loading-spinner"></div>
            <span>加载中...</span>
          </div>
          <div v-else-if="recentOrders.length === 0" class="empty-state">
            <i class="fas fa-inbox"></i>
            <p>暂无订单数据</p>
          </div>
          <div v-else class="orders-list">
            <div 
              v-for="order in recentOrders" 
              :key="order.orderId"
              class="order-item"
            >
              <div class="order-info">
                <div class="order-id">#{{ order.orderId }}</div>
                <div class="order-user">用户ID: {{ order.userId }}</div>
              </div>
              <div class="order-amount">¥{{ formatMoney(order.totalAmount) }}</div>
              <div class="order-status" :class="getOrderStatusClass(order.orderStatus)">
                {{ getOrderStatusText(order.orderStatus) }}
              </div>
              <div class="order-date">{{ formatDate(order.purchaseTime || order.orderDate) }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 热门商品 -->
      <div class="content-card">
        <div class="card-header">
          <h3 class="card-title">热门商品</h3>
          <router-link to="/admin/products" class="view-all-link">
            查看全部 <i class="fas fa-arrow-right"></i>
          </router-link>
        </div>
        <div class="card-content">
          <div v-if="loading.products" class="loading-state">
            <div class="loading-spinner"></div>
            <span>加载中...</span>
          </div>
          <div v-else-if="hotProducts.length === 0" class="empty-state">
            <i class="fas fa-box-open"></i>
            <p>暂无商品数据</p>
          </div>
          <div v-else class="products-list">
            <div 
              v-for="product in hotProducts" 
              :key="product.productId"
              class="product-item"
            >
              <div class="product-image">
                <img 
                  :src="product.productImage || '/ceholder-product.png'" 
                  :alt="product.productName"
                  @error="handleImageError"
                />
              </div>
              <div class="product-info">
                <div class="product-name">{{ product.productName }}</div>
                <div class="product-price">¥{{ formatMoney(product.price) }}</div>
              </div>
              <div class="product-stock">
                <span class="stock-label">库存:</span>
                <span class="stock-value" :class="getStockClass(product.stock)">
                  {{ product.stock }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 系统状态 -->
    <div class="system-status">
      <div class="status-card">
        <div class="status-header">
          <h3>系统状态</h3>
          <div class="status-indicator online">
            <span class="indicator-dot"></span>
            <span>运行正常</span>
          </div>
        </div>
        <div class="status-content">
          <div class="status-item">
            <span class="status-label">服务器状态:</span>
            <span class="status-value success">正常</span>
          </div>
          <div class="status-item">
            <span class="status-label">数据库连接:</span>
            <span class="status-value success">已连接</span>
          </div>
          <div class="status-item">
            <span class="status-label">API响应时间:</span>
            <span class="status-value">{{ apiResponseTime }}ms</span>
          </div>
          <div class="status-item">
            <span class="status-label">最后更新:</span>
            <span class="status-value">{{ formatDate(new Date()) }}</span>
          </div>
        </div>
      </div>
      
      <!-- 快速操作 -->
      <div class="quick-actions">
        <h3>快速操作</h3>
        <div class="actions-grid">
          <router-link to="/admin/products" class="action-button">
            <i class="fas fa-plus"></i>
            添加商品
          </router-link>
          <router-link to="/admin/categories" class="action-button">
            <i class="fas fa-tags"></i>
            管理分类
          </router-link>
          <router-link to="/admin/users" class="action-button">
            <i class="fas fa-users"></i>
            用户管理
          </router-link>
          <router-link to="/admin/orders" class="action-button">
            <i class="fas fa-list"></i>
            订单管理
          </router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { userAPI, productAPI, orderAPI } from '@/api'

export default {
  name: 'DashboardView',
  setup() {
    // 响应式数据
    const stats = reactive({
      totalUsers: 0,
      totalProducts: 0,
      totalOrders: 0,
      totalRevenue: 0
    })
    
    const recentOrders = ref([])
    const hotProducts = ref([])
    const apiResponseTime = ref(0)
    
    const loading = reactive({
      orders: false,
      products: false,
      stats: false
    })
    
    // 方法
    const loadDashboardData = async () => {
      const startTime = Date.now()
      
      try {
        // 并行加载数据
        await Promise.all([
          loadStats(),
          loadRecentOrders(),
          loadHotProducts()
        ])
      } catch (error) {
        console.error('仪表盘数据加载失败:', error)
      } finally {
        apiResponseTime.value = Date.now() - startTime
      }
    }
    
    const loadStats = async () => {
      loading.stats = true
      try {
        // 获取用户统计
        const usersResponse = await userAPI.getAllUsers()
        if (usersResponse.success) {
          stats.totalUsers = usersResponse.users.length
        }
        
        // 获取商品统计
        const productsResponse = await productAPI.getAllProducts()
        if (productsResponse.success) {
          stats.totalProducts = productsResponse.products.length
        }
        
        // 获取订单统计
        const ordersResponse = await orderAPI.getAllOrders()
        if (ordersResponse.success) {
          stats.totalOrders = ordersResponse.orders.length
          // 计算总收入
          stats.totalRevenue = ordersResponse.orders.reduce((total, order) => {
            return total + parseFloat(order.totalAmount || 0)
          }, 0)
        }
      } catch (error) {
        console.error('统计数据加载失败:', error)
      } finally {
        loading.stats = false
      }
    }
    
    const loadRecentOrders = async () => {
      loading.orders = true
      try {
        const response = await orderAPI.getAllOrders()
        if (response.success) {
          // 按日期排序，取最近5个订单
          recentOrders.value = response.orders
            .sort((a, b) => new Date(b.purchaseTime || b.orderDate) - new Date(a.purchaseTime || a.orderDate))
            .slice(0, 5)
        }
      } catch (error) {
        console.error('最近订单加载失败:', error)
      } finally {
        loading.orders = false
      }
    }
    
    const loadHotProducts = async () => {
      loading.products = true
      try {
        const response = await productAPI.getHotProducts()
        if (response.success) {
          hotProducts.value = response.products.slice(0, 5)
        } else {
          // 如果没有热门商品接口，获取所有商品并取前5个
          const allProductsResponse = await productAPI.getAllProducts()
          if (allProductsResponse.success) {
            hotProducts.value = allProductsResponse.products.slice(0, 5)
          }
        }
      } catch (error) {
        console.error('热门商品加载失败:', error)
        // 尝试获取所有商品
        try {
          const allProductsResponse = await productAPI.getAllProducts()
          if (allProductsResponse.success) {
            hotProducts.value = allProductsResponse.products.slice(0, 5)
          }
        } catch (err) {
          console.error('商品数据加载失败:', err)
        }
      } finally {
        loading.products = false
      }
    }
    
    const formatMoney = (amount) => {
      if (!amount) return '0.00'
      return parseFloat(amount).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    }
    
    const formatDate = (date) => {
      if (!date) return '-'
      return new Date(date).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    
    const getOrderStatusText = (status) => {
      const statusMap = {
        'pending': '待处理',
        'paid': '已支付', 
        'confirmed': '已确认',
        'shipped': '已发货',
        'completed': '已完成',
        'cancelled': '已取消',
        '待付款': '待付款',
        '已付款': '已付款',
        '已发货': '已发货',
        '已完成': '已完成',
        '已取消': '已取消'
      }
      return statusMap[status] || status || '未知状态'
    }
    
    const getOrderStatusClass = (status) => {
      const classMap = {
        'pending': 'status-pending',
        'paid': 'status-paid',
        'confirmed': 'status-paid',
        'shipped': 'status-shipped', 
        'completed': 'status-delivered',
        'cancelled': 'status-cancelled',
        '待付款': 'status-pending',
        '已付款': 'status-paid',
        '已发货': 'status-shipped',
        '已完成': 'status-delivered',
        '已取消': 'status-cancelled'
      }
      return classMap[status] || 'status-default'
    }
    
    const getStockClass = (stock) => {
      if (stock <= 0) return 'stock-out'
      if (stock <= 10) return 'stock-low'
      return 'stock-normal'
    }
    
    const handleImageError = (event) => {
  event.target.src = '/ceholder-product.png'
}
    
    // 生命周期
    onMounted(() => {
      loadDashboardData()
    })
    
    return {
      stats,
      recentOrders,
      hotProducts,
      loading,
      apiResponseTime,
      formatMoney,
      formatDate,
      getOrderStatusText,
      getOrderStatusClass,
      getStockClass,
      handleImageError
    }
  }
}
</script>

<style scoped>
.dashboard {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

/* 统计卡片 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.stat-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stat-icon.users {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.stat-icon.products {
  background: linear-gradient(135deg, #f093fb, #f5576c);
}

.stat-icon.orders {
  background: linear-gradient(135deg, #4facfe, #00f2fe);
}

.stat-icon.revenue {
  background: linear-gradient(135deg, #43e97b, #38f9d7);
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 4px;
}

.stat-label {
  color: #7f8c8d;
  font-size: 14px;
}

/* 主要内容区域 */
.main-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
}

.content-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24px 24px 0;
  margin-bottom: 20px;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
}

.view-all-link {
  color: #3498db;
  text-decoration: none;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: color 0.3s ease;
}

.view-all-link:hover {
  color: #2980b9;
}

.card-content {
  padding: 0 24px 24px;
}

/* 加载和空状态 */
.loading-state, .empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #7f8c8d;
}

.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #ecf0f1;
  border-top: 3px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 12px;
  opacity: 0.5;
}

/* 订单列表 */
.orders-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.order-item {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 1.5fr;
  gap: 16px;
  align-items: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 12px;
  transition: background 0.3s ease;
}

.order-item:hover {
  background: #e9ecef;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.order-id {
  font-weight: 600;
  color: #2c3e50;
}

.order-user {
  font-size: 12px;
  color: #7f8c8d;
}

.order-amount {
  font-weight: 600;
  color: #27ae60;
}

.order-status {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
  text-align: center;
}

.status-pending { background: #fff3cd; color: #856404; }
.status-paid { background: #d4edda; color: #155724; }
.status-shipped { background: #cce5ff; color: #004085; }
.status-delivered { background: #d1ecf1; color: #0c5460; }
.status-cancelled { background: #f8d7da; color: #721c24; }
.status-default { background: #e9ecef; color: #495057; }

.order-date {
  font-size: 12px;
  color: #7f8c8d;
}

/* 商品列表 */
.products-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.product-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 12px;
  transition: background 0.3s ease;
}

.product-item:hover {
  background: #e9ecef;
}

.product-image {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  overflow: hidden;
  background: #ecf0f1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.product-name {
  font-weight: 500;
  color: #2c3e50;
  font-size: 14px;
}

.product-price {
  color: #27ae60;
  font-weight: 600;
  font-size: 12px;
}

.product-stock {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
}

.stock-label {
  color: #7f8c8d;
}

.stock-value {
  font-weight: 500;
}

.stock-normal { color: #27ae60; }
.stock-low { color: #f39c12; }
.stock-out { color: #e74c3c; }

/* 系统状态 */
.system-status {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 30px;
}

.status-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.status-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.status-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 18px;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.status-indicator.online {
  color: #27ae60;
}

.indicator-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #27ae60;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

.status-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #ecf0f1;
}

.status-item:last-child {
  border-bottom: none;
}

.status-label {
  color: #7f8c8d;
  font-size: 14px;
}

.status-value {
  font-weight: 500;
  color: #2c3e50;
  font-size: 14px;
}

.status-value.success {
  color: #27ae60;
}

/* 快速操作 */
.quick-actions {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.quick-actions h3 {
  margin: 0 0 20px 0;
  color: #2c3e50;
  font-size: 18px;
}

.actions-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.action-button {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 20px 16px;
  background: #f8f9fa;
  border-radius: 12px;
  text-decoration: none;
  color: #2c3e50;
  transition: all 0.3s ease;
  font-size: 14px;
}

.action-button:hover {
  background: #e9ecef;
  transform: translateY(-2px);
}

.action-button i {
  font-size: 20px;
  color: #3498db;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-grid {
    grid-template-columns: 1fr;
  }
  
  .system-status {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .order-item {
    grid-template-columns: 1fr;
    gap: 8px;
  }
  
  .actions-grid {
    grid-template-columns: 1fr;
  }
}
</style> 